package com.jiazhong.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.commons.Mapper.UserMapper;
import com.jiazhong.commons.Util.JsonResult;
import com.jiazhong.commons.Util.ResultTool;
import com.jiazhong.commons.Util.StringUtil;
import com.jiazhong.commons.bean.User;
import com.jiazhong.commons.config.JwtConfig;
import com.jiazhong.commons.exception.LoginFailException;
import com.jiazhong.commons.exception.PasswordErrorException;
import com.jiazhong.commons.exception.UsernameNotFoundException;
import com.jiazhong.front.service.AuthService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthServiceImpl extends ServiceImpl<UserMapper, User> implements AuthService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(User user) {
        // 查询数据库 select * from xxx where user=?
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("status", "1");
        User one = getOne(wrapper);
        if (one == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        log.info("数据库密码是:{}", one.getPassword());
        String inputPass = StringUtil.encryptMD5(user.getPassword());
        log.info("输入的密码是:{}", inputPass);
        if (!Objects.equals(inputPass, one.getPassword())) {
            throw new PasswordErrorException("密码输入错误");
        }
        String token = JwtConfig.getJwtToken(one);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("front_token:" + one.getId(), token, 1, TimeUnit.DAYS);
        return ResultTool.success(token);
    }

    @Override
    public JsonResult logout(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b){
            throw new LoginFailException("用户没有登录");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object id = claims.get("id");
        stringRedisTemplate.delete("front_token:" + id);
        return ResultTool.success("success");
    }

    @Override
    public JsonResult register(User user) {
        user.setPassword(StringUtil.encryptMD5(user.getPassword()));
        save(user);
        return ResultTool.success("success");
    }
}
